package com.yuxin.tongyi.lsll.thread;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;

import android.content.Context;
import android.os.Message;

import com.yuxin.tongyi.lsll.common.Constants;
import com.yuxin.tongyi.lsll.pojo.EventInfo;
import com.yuxin.tongyi.lsll.pojo.EventInfos;
import com.yuxin.tongyi.lsll.pojo.LoginInfo;
import com.yuxin.tongyi.lsll.util.FileTool;
import com.yuxin.tongyi.lsll.util.HttpRequestUtil;
import com.yuxin.tongyi.lsll.util.PubUtil;

/**
 * @author ww
 * @date:2012-4-7 上午10:57:57
 * @Desc:  获取服务器事件信息并保存本地
 * @version :
 * 
 */
public class SaveEventDataThread implements Runnable {

	private Context context;
	private HttpRequestUtil request;
	private LoginInfo loginInfo;
	
	public SaveEventDataThread(Context context, LoginInfo loginInfo){
		this.context = context;
		this.loginInfo = loginInfo;
		
		request = new HttpRequestUtil();
	}
	
	@Override
	public void run() {
		try{
			boolean flag = request.eventListRequest(loginInfo.getLoginName(), loginInfo.getPassword()); // 请求事件列表
			String status = request.getStatus();
			if (flag) {// 服务器响应
				if (status != null && !"".equals(status)) {
					Message msg = new Message();
					List<Object> objects = request.getObjList();
					if (objects != null && objects.size() > 0) { // 服务器正确响应数据
						Object obj = objects.get(0);
						if (obj instanceof EventInfos) {
							EventInfos eventInfo = (EventInfos) obj;
							ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
							ObjectOutputStream oStream;
							try {
								oStream = new ObjectOutputStream(baoStream);
								oStream.writeObject(eventInfo);
							} catch (IOException e) {
								e.printStackTrace();
							}
							//获取第一个事件
							String firstEvent = FileTool.getObjectToString(eventInfo.getEventInfo().get(0));
							String eventInfos = new String(org.apache.commons.codec.binary.Base64.encodeBase64(baoStream.toByteArray()));
							PubUtil.setConfigValue(context, Constants.CFG_EVENT_FIRST, firstEvent);
							PubUtil.setConfigValue(context, Constants.CFG_EVENT_DATA, eventInfos);
							PubUtil.setConfigValue(context, Constants.CFG_EVENT_STATE, Constants.TH_EVENT_ON);
						}
						
					} else { // 其他信息
						PubUtil.setConfigValue(context, Constants.CFG_EVENT_STATE, Constants.TH_EVENT_EMPTY);
					}
				} else {
					PubUtil.setConfigValue(context, Constants.CFG_EVENT_STATE, Constants.TH_EVENT_ERROR);
				}
			}else { // 访问服务器失败
				PubUtil.setConfigValue(context, Constants.CFG_EVENT_STATE, Constants.TH_EVENT_OFF);
			}

		}catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
